//TodoUI类 - 处理所有与UI相关的操作

class TodoUI{
      /**
     * 构造函数
     * @param {HTMLElement} todoListContainer - 任务列表容器元素
     * @param {HTMLElement} emptyListElement - 空列表提示元素
     */

          constructor(todoListContainer, emptyListElement) {
        this.todoListContainer = todoListContainer;
        this.emptyListElement = emptyListElement;
        this.currentFilter = 'all'; // 默认过滤器
        this.searchTerm = ''; // 搜索关键词
    }


        /**
     * 渲染整个任务列表
     * @param {Array} todos - 任务数组
     */
    renderTodoList(todos) {
        // 过滤任务
        const filteredTodos = this.filterTodos(todos);
        
        // 清空列表容器，保留空列表提示
        const emptyListElement = this.emptyListElement;
        this.todoListContainer.innerHTML = '';
        
        // 显示或隐藏空列表提示
        if (filteredTodos.length === 0) {
            emptyListElement.style.display = 'block';
        } else {
            emptyListElement.style.display = 'none';
            
            // 添加过滤后的任务项到列表
            filteredTodos.forEach(todo => {
                this.todoListContainer.appendChild(this.createTodoElement(todo));
            });
        }
        
        // 更新任务计数
        this.updateTodoCounts(todos);
    }

      /**
     * 根据当前过滤器和搜索条件过滤任务
     * @param {Array} todos - 所有任务
     * @returns {Array} 过滤后的任务
     */


          filterTodos(todos) {
        // 首先按搜索词过滤
        let filtered = todos;
        if (this.searchTerm) {
            const term = this.searchTerm.toLowerCase();
            filtered = todos.filter(todo => 
                todo.title.toLowerCase().includes(term) || 
                (todo.description && todo.description.toLowerCase().includes(term))
            );
        }
        
        // 然后按状态过滤
        switch (this.currentFilter) {
            case 'active':
                return filtered.filter(todo => !todo.completed);
            case 'completed':
                return filtered.filter(todo => todo.completed);
            default:
                return filtered;
        }
    }


        /**
     * 设置当前过滤器
     * @param {string} filter - 过滤器类型 ('all', 'active', 'completed')
     */
    setFilter(filter) {
        this.currentFilter = filter;
    }


        /**
     * 设置搜索关键词
     * @param {string} term - 搜索关键词
     */
    setSearchTerm(term) {
        this.searchTerm = term;
    }

     /**
     * 创建单个任务的HTML元素
     * @param {Object} todo - 任务对象
     * @returns {HTMLElement} 任务项元素
     */

        createTodoElement(todo) {
        const todoItem = document.createElement('div');
        todoItem.className = `list-group-item todo-item ${todo.completed ? 'completed' : ''}`;
        todoItem.dataset.id = todo.id;
        
        if (todo.priority === '高') {
            todoItem.classList.add('high-priority');
        } else if (todo.priority === '中') {
            todoItem.classList.add('medium-priority');
        } else if (todo.priority === '低') {
            todoItem.classList.add('low-priority');
        }
        
        // 创建任务内容
        const todoContent = document.createElement('div');
        todoContent.className = 'card-body d-flex justify-content-between align-items-start';
        
        // 左侧：复选框和任务信息
        const leftSection = document.createElement('div');
        leftSection.className = 'd-flex align-items-start';
        
            // 复选框
        const checkbox = document.createElement('div');
        checkbox.className = 'form-check me-3';
        checkbox.innerHTML = `
            <input class="form-check-input toggle-status" type="checkbox" 
                id="checkbox-${todo.id}" ${todo.completed ? 'checked' : ''}>
        `;

        // 任务信息
        const todoInfo = document.createElement('div');
        todoInfo.className = 'ms-2';
        todoInfo.innerHTML = `
            <h5 class="todo-title">${this.escapeHTML(todo.title)}</h5>
            ${todo.description ? `<p class="todo-description">${this.escapeHTML(todo.description)}</p>` : ''}
            <div class="todo-meta">
                <span class="priority-badge ${todo.priority === '高' ? 'high' : todo.priority === '中' ? 'medium' : 'low'}">
                    ${todo.priority}优先级
                </span>
                <span>创建于: ${this.formatDate(todo.created_at || new Date())}</span>
            </div>
        `;

            leftSection.appendChild(checkbox);
        leftSection.appendChild(todoInfo);
        
        const todoActions = document.createElement('div');
        todoActions.className = 'todo-actions';
        todoActions.innerHTML = `
            <button class="btn btn-sm btn-outline-primary edit-btn">
                <i class="bi bi-pencil"></i> 编辑
            </button>
            <button class="btn btn-sm btn-outline-danger delete-btn">
                <i class="bi bi-trash"></i> 删除
            </button>
        `;
        
        todoContent.appendChild(leftSection);
        todoContent.appendChild(todoActions);
        todoItem.appendChild(todoContent);
        
        return todoItem;
    }


     /**
     * 更新任务计数显示
     * @param {Array} todos - 所有任务数组
     */
    updateTodoCounts(todos) {
        const totalCount = todos.length;
        const completedCount = todos.filter(todo => todo.completed).length;
        const activeCount = totalCount - completedCount;
        
        document.getElementById('total-count').textContent = totalCount;
        document.getElementById('completed-count').textContent = completedCount;
        document.getElementById('active-count').textContent = activeCount;
    }

     /**
     * 添加单个任务到列表
     * @param {Object} todo - 新任务对象
     * @param {Array} allTodos - 所有任务的数组
     */
    addTodoToList(todo, allTodos) {
        // 隐藏空列表提示
        this.emptyListElement.style.display = 'none';
        
        // 检查当前过滤器是否应该显示这个新任务
        const shouldShow = this.shouldShowTodo(todo);
        
        if (shouldShow) {
            const todoElement = this.createTodoElement(todo);
            this.todoListContainer.insertBefore(todoElement, this.todoListContainer.firstChild);
        }
        
        // 更新计数
        this.updateTodoCounts(allTodos);
    }

    /**
     * 检查任务是否应该在当前过滤条件下显示
     * @param {Object} todo - 任务对象
     * @returns {boolean} 是否应该显示
     */
    shouldShowTodo(todo) {
        // 检查搜索条件
        if (this.searchTerm) {
            const term = this.searchTerm.toLowerCase();
            const matchesSearch = todo.title.toLowerCase().includes(term) || 
                                (todo.description && todo.description.toLowerCase().includes(term));
            if (!matchesSearch) return false;
        }
        
     
        switch (this.currentFilter) {
            case 'active':
                return !todo.completed;
            case 'completed':
                return todo.completed;
            default:
                return true;
        }
    }

       /**
     * 从列表中移除任务
     * @param {string|number} todoId - 任务ID
     * @param {Array} allTodos - 所有任务的数组
     */
    removeTodoFromList(todoId, allTodos) {
        const todoElement = this.todoListContainer.querySelector(`[data-id="${todoId}"]`);
        if (todoElement) {
            this.todoListContainer.removeChild(todoElement);
        }
        
        if (allTodos.length === 0) {
            this.emptyListElement.style.display = 'block';
        }
        
        // 更新计数
        this.updateTodoCounts(allTodos);
    }

       updateTodoElement(todo, allTodos) {
        const todoElement = this.todoListContainer.querySelector(`[data-id="${todo.id}"]`);
        
        const shouldShow = this.shouldShowTodo(todo);
        
        if (todoElement) {
            if (shouldShow) {
                const newTodoElement = this.createTodoElement(todo);
                this.todoListContainer.replaceChild(newTodoElement, todoElement);
            } else {
                this.todoListContainer.removeChild(todoElement);
            }
        } else if (shouldShow) {
            const newTodoElement = this.createTodoElement(todo);
            this.todoListContainer.appendChild(newTodoElement);
        }
        
        
        this.updateTodoCounts(allTodos);
    }

        /**
     * 填充编辑模态框表单
     * @param {Object} todo - 待编辑的任务对象
     */
    fillEditModal(todo) {
        document.getElementById('edit-todo-id').value = todo.id;
        document.getElementById('edit-todo-title').value = todo.title;
        document.getElementById('edit-todo-description').value = todo.description || '';
        document.getElementById('edit-todo-priority').value = todo.priority;
        document.getElementById('edit-todo-completed').checked = todo.completed;
    }

        /**
     * 格式化日期
     * @param {Date|string} date - 日期对象或日期字符串
     * @returns {string} 格式化后的日期字符串
     */
    formatDate(date) {
        const d = new Date(date);
        return d.toLocaleString('zh-CN', { 
            year: 'numeric', 
            month: '2-digit', 
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
        });
    }

        /**
     * 转义HTML特殊字符，防止XSS攻击
     * @param {string} html - 输入字符串
     * @returns {string} 转义后的安全字符串
     */
    escapeHTML(html) {
        return html
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;");
    }
}

window.TodoUI = TodoUI; 
